package com.wondream.myframework.app.jade.http.request;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.domain.Pageable;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * PageRequest.
 * <p>
 * create on 2023-07-24
 *
 * @author <a href="mailto:xianwei.wang@jadefortune.com.cn">wangxianwei</a>
 * @since 2.2.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public final class PageRequest {

    @NotNull(message = "page不能为空")
    @Min(value = 1, message = "page最小为{value}")
    @ApiModelProperty(name = "page", value = "页码", required = true)
    private Integer page;

    @Size(message = "size须在{min}-{max}之间", min = 1, max = 500)
    @ApiModelProperty(name = "size", value = "分页数量", required = true)
    private Integer size;

    // TODO 扩展 排序功能

    public static PageRequest of(int page, int size) {
        return new PageRequest(Math.max(page, 1), Math.max(size, 1));
    }

    /**
     * 转换为JPA使用的分页对象
     *
     * @param pageRequest {@link PageRequest}
     * @return {@link Pageable}
     */
    public static Pageable convert(PageRequest pageRequest) {
        return org.springframework.data.domain.PageRequest.of(pageRequest.getPage(), pageRequest.getSize());
    }
}
